<template>
  <div class="cancel-page">
    <!-- 顶部导航 -->
    <div class="page-header">
      <el-button 
        icon="ArrowLeft" 
        size="small" 
        @click="handleGoBack"
        class="back-btn"
      />
      <h2 class="page-title">提前退房</h2>
    </div>

    <!-- 状态提示 -->
    <el-alert 
      title="提示" 
      type="warning" 
      :closable="false"
      class="status-alert"
    >
     您正在申请提前退房，系统将根据酒店退房规则自动计算退款金额
    </el-alert>

    <!-- 订单信息 -->
    <el-card class="info-card">
      <div class="order-info">
        <h3 class="hotel-name">{{ hotelName }}</h3>
        <p class="hotel-address">{{ hotelAddress }}</p>
        
        <div class="info-row">
          <span class="info-label">订单号：</span>
          <span class="info-value">{{ orderNumber }}</span>
        </div>
        
        <div class="info-row">
          <span class="info-label">入住时间：</span>
          <span class="info-value">
            {{ formatDate(checkIn) }} - {{ formatDate(checkOut) }}
            （共{{ getStayNights() }}晚）
          </span>
          
        </div>
        
        <div class="info-row">
          <span class="info-label">房型：</span>
          <span class="info-value">{{ roomtypeName }} × {{ roomQuantity }}间</span>
        </div>
        
        <div class="info-row">
          <span class="info-label">实付金额：</span>
          <span class="info-value price-red">¥{{ orderPrice }}</span>
        </div>
      </div>
    </el-card>

    <!-- 提前退房规则 -->
<el-card class="rule-card" header="提前退房规则">
  <div class="cancel-policy-card">
    <h3 class="policy-title">订单退订政策</h3>

    <!-- 遍历提前退房规则 -->
    <ul class="policy-list">
      <li 
        v-for="rule in CheckoutEarly.filter(r => r.cancelType === '提前退房')" 
        :key="rule.cancelId" 
        class="policy-item"
      >
        <div class="policy-header">
          <strong class="policy-type">{{ rule.cancelType }}</strong>
          <span class="policy-fee">扣费率：{{ (rule.feeRate * 100).toFixed(0) }}%</span>
        </div>
        <p class="policy-desc">{{ rule.ruleDesc }}</p>
      </li>
    </ul>
  </div>
</el-card>

    <!-- 提前退房费用计算 -->
    <el-card class="calculation-card" header="提前退房费用计算">
      <!-- 原计划入住晚数 -->
      <div class="calc-item">
        <span class="calc-label">原计划入住晚数:</span>
        <span class="calc-value">{{ totalNights }}晚</span>
      </div>
       <!-- 已入住晚数 -->
  <div class="calc-item">
    <span class="calc-label">已入住：</span>
    <span class="calc-value">{{ totalNights - daysDiff }}晚</span>
  </div>

        <!-- 剩余未住天数 -->
        <div class="calc-item">
          <span class="calc-label">剩余未住：</span>
          <span class="calc-value">{{ daysDiff }}晚</span>
        </div>

        <!-- 每晚房价 -->
        <div class="calc-item">
          <span class="calc-label">每晚房价：</span>
          <span class="calc-value">¥{{ pricePerNight.toFixed(2) }}</span>
        </div>

       <!-- 违约金 -->
        <div class="calc-item">
          <span class="calc-label">违约金：</span>
          <span class="calc-value price-red">¥{{ penaltyAmount.toFixed(2) }}</span>
        </div>

        <!-- 可退款金额 -->
        <div class="calc-item">
          <span class="calc-label">可退款金额：</span>
          <span class="calc-value price-green">¥{{ refundAmount.toFixed(2) }}</span>
        </div>

        <el-alert 
          type="info" 
          size="small"
          class="refund-note"
          :closable="false"
          description="退款将在3-7个工作日内原路退回"
        />
      </el-card>

    <!-- 操作按钮 -->
    <div class="btn-group">
      <el-button 
        @click="toOrderDetail"
        class="back-button"
        
        >
        返回订单详情
      </el-button>
      <el-button 
        type="danger" 
        @click="showDialog = true"
        :disabled="isProcessing"
        class="confirm-button"
      >
        确认取消订单
      </el-button>
    </div>

    <!-- 确认弹窗 -->
    <el-dialog
      v-model="showDialog"
      title="确认取消订单？"
      width="300px"
    >
      <div class="dialog-content">
        <p>订单号：{{ orderNumber }}</p>
        <p>违约金：¥{{ penaltyAmount.toFixed(2) }}</p>
        <p>可退款：¥{{ refundAmount.toFixed(2) }}</p>
        <el-alert 
          type="warning" 
          size="small"
          :closable="false"
          class="dialog-warning"
          description="订单取消后不可恢复，请谨慎操作"
        />
      </div>
      <template #footer>
        <el-button @click="showDialog = false">取消</el-button>
        <el-button 
          type="danger" 
          @click="handleConfirmCancel"
          :loading="isProcessing"
        >
          确认取消
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue';
import { ElButton, ElCard, ElAlert, ElDialog, ElMessage } from 'element-plus';
import { ArrowLeft } from '@element-plus/icons-vue';
import dayjs from 'dayjs';
import { useRoute, useRouter } from "vue-router";
import {orderCancelRules} from "@/api/order-cancel-rules.js";
import { createToken } from '../api/autoIdempotent.js'
import { refundOrder } from '../api/refunds.js'


const router = useRouter();
const route = useRoute();

// 订单信息
const hotelId = route.query.hotelId;
const orderId = route.query.orderId;
const hotelName = route.query.hotelName;
const hotelAddress = route.query.hotelAddress;
const orderNumber = route.query.orderNumber;

const roomtypeName = route.query.roomtypeName;
//商品价格
const proPrice = route.query.proPrice;
const roomQuantity = route.query.roomQuantity;
//订单价格
const orderPrice = route.query.orderPrice;
// 响应式数据（与数据库字段对应）
const order = reactive({
  orderId: null,
  orderNumber: '',
  hotelId: null,
  orderStatus: '已支付'
});

const orderDetail = reactive({
  checkIn: '',
  checkOut: '',
  roomtypeId: null,
  roomQuantity: 1
});

const hotelInfo = reactive({
  hotelName: '',
  province: '',
  city: '',
  county: '',
  street: ''
});

const roomType = reactive({
  roomtypeName: ''
});

// token 防重复提交
const formToken = ref('')

// 生成幂等 token
async function createFormToken() {
  try {
    const res = await createToken()
    formToken.value = res.data.data
    console.log("formToken=", formToken.value)
  } catch (err) {
    console.error("生成token失败", err)
    alert('生成token失败，请刷新页面重试')
  }
}

const paymentRecord = reactive({
  amount: 0   
});
//违约金计算
const matchedRule = ref({});
const penaltyAmount = ref(0);
const refundAmount = ref(0);
const actualCheckout = ref(dayjs());//当前日期
const checkIn = route.query.checkIn;
const checkOut = route.query.checkOut;
const totalAmount = ref(Number(route.query.orderPrice));//实付总金额
const totalNights = ref(0);// 总晚数
const getStayNights = () =>{
  if(orderDetail.checkIn && orderDetail.checkOut){
    return dayjs(orderDetail.checkOut).diff(dayjs(orderDetail.checkIn),'day');
  }
  return 0;
};
const pricePerNight = ref(0)//每晚价格
const calculatePricePerNigt = () =>{
  totalNights.value = getStayNights();
  if(totalNights.value > 0){
    pricePerNight.value = totalAmount.value / totalNights.value;
  }else{
    pricePerNight.value = 0;
  }
};
// 剩余天数
const daysDiff = ref(0);
const calculateDaysDifference = () => {
  const checkOutDate = dayjs(orderDetail.checkOut);//原计划离店日期
  const currentDate = actualCheckout.value; //当前时间(提前退房日期)
  daysDiff.value = checkOutDate.diff(currentDate, 'day');
  if (daysDiff.value < 0) daysDiff.value = 0; //防止出现负数
};
// 状态控制
const showDialog = ref(false);
const isProcessing = ref(false);

// 订单政策
let CheckoutEarly = ref([])
onMounted(()=>{
  console.log("当前日期:", actualCheckout.value.format("YYYY-MM-DD HH:mm:ss"));
    getCheckoutEarly();
    loadOrderData();
    calculateDaysDifference();
    calculatePricePerNigt();
});
// loadOrderData 用于加载订单数据
async function loadOrderData() {
  // 从 route.query 获取订单数据并赋值
  orderDetail.checkIn = route.query.checkIn;
  orderDetail.checkOut = route.query.checkOut;
  orderDetail.roomtypeName = route.query.roomtypeName;
  orderDetail.roomQuantity = route.query.roomQuantity;
}
async function getCheckoutEarly(){
    const response = await orderCancelRules()
    CheckoutEarly.value = response.data.data;
      matchedRule.value = CheckoutEarly.value.find(r => r.cancelType === '提前退房') || { feeRate: 0 };

    // 计算违约金与退款金额
    calculatePenalty();
}
// 计算违约金
const calculatePenalty = () => {
  const totalAmount = Number(orderPrice); //总价
  const penaltyRate = matchedRule.value.feeRate || 0;//违约扣费比例
  // 计算每晚价格
  totalNights.value = dayjs(checkOut).diff(dayjs(checkIn),'day');
  pricePerNight.value = totalNights.value > 0 ? totalAmount / totalNights.value : 0;
  // 计算剩余未住晚数
  const stayedNights = totalNights.value - daysDiff.value; //已入住晚数
  const stayedCost = pricePerNight.value * stayedNights; //已入住费用
  const unusedCost = pricePerNight.value * daysDiff.value; //为入住的费用
  //计算违约金
  penaltyAmount.value = Number((unusedCost * penaltyRate).toFixed(2));
  //可退款金额
  refundAmount.value = Number((unusedCost - penaltyAmount.value).toFixed(2));
  console.log("===== 退款计算明细 =====");
  console.log("总价:", totalAmount);
  console.log("总晚数:", totalNights.value);
  console.log("已入住晚数:", stayedNights);
  console.log("剩余未住:", daysDiff.value);
  console.log("每晚房价:", pricePerNight.value);
  console.log("未住部分费用:", unusedCost);
  console.log("违约扣费率:", penaltyRate);
  console.log("违约金:", penaltyAmount.value);
  console.log("可退款金额:", refundAmount.value);
};

// 格式化日期
const formatDate = (dateStr) => dayjs(dateStr).                                                                                                                                                format('YYYY-MM-DD');


// 页面交互
const handleGoBack = () => console.log('返回订单详情页');
// 点击确认取消订单
const handleConfirmCancel = async () => {
  isProcessing.value = true;

  await createFormToken(); // 确保 formToken.value 已有值

  // 构造退款参数
  const payload = {
    orderNumber: orderNumber,
    orderId: orderId,
    refundAmount: refundAmount.value,
    refundReason: '用户提前取消订单'
  };

try {
  const res = await refundOrder(payload, formToken.value);

  console.log('退款接口返回:', res.data);

  if (res.data.code === 200) {
    // 退款成功
    ElMessage.success(res.data.data || '退款成功');
    showDialog.value = false;
    router.push(`/orderDetail/${orderId}`);
  } else {
    // 退款失败
    ElMessage.error(res.data.message || '退款失败');
  }
} catch (err) {
  console.error('退款接口调用异常:', err);
  ElMessage.error('退款接口调用异常');
} finally {
  isProcessing.value = false;
}

};



//点击返回订单详情
function toOrderDetail(){
  router.push(`/orderDetail/${orderId}`)
}
</script>

<style scoped>
.cancel-page {
  padding: 16px;
  max-width: 600px;
  margin: 0 auto;
  background-color: #f9f9f9;
  min-height: 100vh;
}

.page-header {
  display: flex;
  align-items: center;
  margin-bottom: 16px;
  padding-bottom: 8px;
  border-bottom: 1px solid #eee;
}

.back-btn {
  margin-right: 12px;
}

.page-title {
  font-size: 18px;
  font-weight: 500;
  margin: 0;
}

.status-alert {
  margin-bottom: 16px;
}

.info-card, .rule-card, .calculation-card {
  margin-bottom: 16px;
  border-radius: 4px;
  border: 1px solid #e5e7eb;
}

.order-info {
  padding: 12px 0;
}

.hotel-name {
  margin: 0 0 8px 0;
  font-size: 16px;
  font-weight: 500;
}

.hotel-address {
  color: #666;
  margin: 0 0 16px 0;
  font-size: 14px;
}

.info-row {
  display: flex;
  margin-bottom: 8px;
  font-size: 14px;
}

.info-label {
  color: #666;
  width: 90px;
  flex-shrink: 0;
}

.info-value {
  flex-grow: 1;
}

.rule-item {
  padding: 12px;
  margin-bottom: 8px;
  border-radius: 4px;
  background-color: #f9f9f9;
}

.rule-item.matched-rule {
  background-color: #fff8f0;
  border: 1px solid #ffe7cc;
}

.rule-header {
  display: flex;
  justify-content: space-between;
  margin-bottom: 4px;
  font-weight: 500;
}

.rule-type {
  color: #e67700;
}

.rule-content {
  font-size: 14px;
}

.fee-rate {
  margin: 4px 0 0 0;
  color: #d93025;
}

.calc-item {
  display: flex;
  justify-content: space-between;
  padding: 6px 0;
  border-bottom: 1px dashed #eee;
}

.calc-item:last-child {
  border-bottom: none;
}

.calc-label {
  color: #666;
}

.refund-note {
  margin-top: 12px;
}

.btn-group {
  display: flex;
  gap: 12px;
  margin-top: 20px;
}

.back-button, .confirm-button {
  flex: 1;
  padding: 10px 0;
}

.price-red {
  color: #d93025;
  font-weight: 500;
}

.price-green {
  color: #10b981;
  font-weight: 500;
}

.dialog-content {
  font-size: 14px;
  line-height: 1.6;
}

.dialog-warning {
  margin-top: 12px;
}
.cancel-page {
  padding: 24px;
  max-width: 960px; /* 原来是 600px，这里加宽 */
  margin: 20px auto; /* 保持居中 */
  background-color: #f9f9f9;
  min-height: 100vh;
  border-radius: 8px; /* 让页面边角稍微圆润一些 */
}

</style>